'''
中间件
'''
from django.utils.deprecation import MiddlewareMixin
from web import models
from django.conf import settings
from django.shortcuts import render, redirect, HttpResponse
import datetime


class Tracer():
    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None


class auth_middleware(MiddlewareMixin):

    def process_request(self, request):
        user_id = request.session.get('user_id', 0)
        user_obj = models.UserInfo.objects.filter(id=user_id).first()
        # 实例化对象
        request.tracer = Tracer()
        # 赋值
        request.tracer.user = user_obj
        # print(request.path_info)
        # 登录验证
        # 在白名单放行，不在跳转
        if request.path_info in settings.LOGIN_WHITE_LIST:
            return
        if not request.tracer.user:
            return redirect('login')

        # 获取用户当前额度
        # 去记录表中查寻记录，以-id排序，并获取最大的 ，以end_time 小于当前时间判断
        transact_obj = models.Transact.objects.filter(user=request.tracer.user, status=2).order_by('-id').first()
        current_time = datetime.datetime.now()
        # 过期了
        if transact_obj.end_datetime and transact_obj.end_datetime < current_time:
            # 免费版的
            transact_obj = models.Transact.objects.filter(user=request.tracer.user, status=2).order_by('id').first()
        # 当前用户的额度
        request.tracer.price_policy = transact_obj.price_policy

    def process_view(self, request, view, args, kwargs):
        # 捕获以manage开头的项目的url，目的去使，未进入manage的视图可以使用项目的id，因为没有进去，无法获得项目id，
        # 是否以manage开头的 如果是则判断是否自己的项目，接着判断是我参与的项目还是我创建的

        if not request.path_info.startswith('/manage/'):
            return
        # 获取项目的id url那里的
        project_id = kwargs.get('project_id')
        # 我创建的
        project_obj = models.Project.objects.filter(creator=request.tracer.user, id=project_id).first()
        if project_obj:
            request.tracer.project = project_obj
            return
        project_user_obj = models.ProjectUser.objects.filter(user=request.tracer.user, project_id=project_id).first()
        if project_user_obj:
            request.tracer.project = project_user_obj.project
            return
        return redirect('project_list')
